<template>
  <div class="carousel-container">
    <div class="carousel">
      <button class="nav-button prev" @click="prevSlide">&#8249;</button>
      <div class="carousel-track-container">
        <div
          class="carousel-track"
          ref="carouselTrack"
          :style="{
            transitionProperty: isTransform ? 'transform' : 'none',
            transform: `translateX(${offset}px)`,
          }"
        >
          <div
            v-for="(item, index) in displayedItems"
            :key="index"
            class="carousel-slide"
            :style="{
              transitionProperty: isTransform ? 'width' : 'none',
            }"
            :class="{ active: isActive(index) }"
            @click="setActiveSlide(index)"
          >
            <div class="slide-content">
              <div class="card-number">{{ getItemNumber(index) }}</div>
              <slot :item="item" :index="index" :active="isActive(index)">
                <div class="default-card">
                  <h3>{{ item.title }}</h3>
                  <p>{{ item.description }}</p>
                </div>
              </slot>
            </div>
          </div>
        </div>
      </div>
      <button class="nav-button next" @click="nextSlide">&#8250;</button>
    </div>
    <div class="indicators">
      <div
        v-for="(item, index) in items"
        :key="index"
        class="indicator"
        :class="{ active: currentRealIndex === index }"
        @click="goToSlide(index)"
      ></div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Carousel",
  props: {
    items: {
      type: Array,
      required: true,
      default: () => [],
    },
    // 是否自动播放
    autoplay: {
      type: Boolean,
      default: false,
    },
    // 自动播放间隔（毫秒）
    autoplayInterval: {
      type: Number,
      default: 3000,
    },
  },
  data() {
    return {
      currentIndex: 2, // 默认从第3个开始（前面有2个克隆项）
      offset: 0,
      autoplayTimer: null,
      isTransform: true,
    };
  },
  computed: {
    // 当前真实索引（相对于原始数组）
    currentRealIndex() {
      if (this.items.length <= 0) return 0;

      // 计算真实索引
      if (this.currentIndex < 2) {
        return this.items.length - (2 - this.currentIndex);
      } else if (this.currentIndex > this.items.length + 1) {
        return this.currentIndex - this.items.length - 2;
      } else {
        return this.currentIndex - 2;
      }
    },

    // 处理无缝循环显示的项目（前后各添加2个）
    displayedItems() {
      if (this.items.length <= 1) return this.items;

      const len = this.items.length;

      // 在开头添加最后2个项目，在结尾添加前2个项目
      return [
        this.items[len - 2], // 倒数第二个项目
        this.items[len - 1], // 最后一个项目
        ...this.items, // 所有原始项目
        this.items[0], // 第一个项目
        this.items[1], // 第二个项目
      ];
    },
  },
  mounted() {
    this.resetOffset();

    // 添加键盘事件监听
    window.addEventListener("keydown", this.handleKeydown);

    // 如果启用自动播放，设置定时器
    if (this.autoplay) {
      this.startAutoplay();
    }
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener("keydown", this.handleKeydown);

    // 清除自动播放定时器
    if (this.autoplayTimer) {
      clearInterval(this.autoplayTimer);
      this.autoplayTimer = null;
    }
  },
  methods: {
    // 处理键盘事件
    handleKeydown(e) {
      if (e.key === "ArrowLeft") {
        this.prevSlide();
      } else if (e.key === "ArrowRight") {
        this.nextSlide();
      }
    },

    // 开始自动播放
    startAutoplay() {
      if (this.autoplayTimer) {
        clearInterval(this.autoplayTimer);
      }

      this.autoplayTimer = setInterval(() => {
        this.nextSlide();
      }, this.autoplayInterval);
    },

    // 获取卡片显示的数字
    getItemNumber(index) {
      if (this.items.length <= 0) return 0;

      // 计算真实项目索引
      if (index < 2) {
        return this.items.length - (2 - index);
      } else if (index > this.items.length + 1) {
        return index - this.items.length - 2;
      } else {
        return index - 2;
      }
    },

    // 判断是否为当前活动卡片
    isActive(index) {
      return index === this.currentIndex;
    },

    // 设置当前活动卡片
    setActiveSlide(index) {
      if (this.isActive(index)) return;

      if (index < this.currentIndex) {
        this.prevSlide();
      } else {
        this.nextSlide();
      }
    },

    // 切换到指定幻灯片
    goToSlide(index) {
      // 转换为显示数组中的索引
      this.currentIndex = index + 2;
      this.resetOffset();
    },

    // 切换到上一张
    prevSlide() {
      if (this.items.length <= 1) return;

      this.currentIndex--;
      this.isTransform = true;

      // 检查是否到达克隆的开头项目
      if (this.currentIndex < 2) {
        // 先无动画跳转到结尾的克隆项目
        this.isTransform = false;
        this.$refs.carouselTrack.clientHeight;
        this.currentIndex = this.displayedItems.length - 2;
        this.resetOffset();

        // 下一帧再平滑过渡到正确位置
        this.$nextTick(() => {
          setTimeout(() => {
            this.prevSlide();
          });
        });
      } else {
        this.resetOffset();
      }
    },

    // 切换到下一张
    nextSlide() {
      if (this.items.length <= 1) return;

      this.currentIndex++;
      this.isTransform = true;

      // 检查是否到达克隆的结尾项目
      if (this.currentIndex >= this.displayedItems.length - 2) {
        // 先无动画跳转到开头的克隆项目
        this.isTransform = false;
        this.$refs.carouselTrack.clientHeight; // 强制回流
        this.currentIndex = 1;
        this.resetOffset();

        // 下一帧再平滑过渡到正确位置
        this.$nextTick(() => {
          setTimeout(() => {
            this.nextSlide();
          });
        });
      } else {
        this.resetOffset();
      }
    },
    // 重置偏移量
    resetOffset() {
      if (this.items.length <= 1) {
        this.offset = 0;
        return;
      }

      // 计算偏移量，使当前卡片位于中间
      const baseOffset = 1200 / 2 - 540 / 2; // 居中中间卡片
      const slideOffset = this.currentIndex * 320; // 每张卡片偏移量

      this.offset = baseOffset - slideOffset;
    },
  },
  watch: {
    items() {
      this.currentIndex = 2;
      this.resetOffset();
    },
  },
};
</script>

<style scoped>
.carousel-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 20px 0;
}

.carousel {
  position: relative;
  width: 1200px;
  display: flex;
  align-items: center;
  margin: 0 auto;
}

.carousel-track-container {
  width: 1200px;
  overflow: hidden;
}

.carousel-track {
  display: flex;
  transition-property: transform;
  transition-duration: 0.3s;
  transition-timing-function: ease;
}

.carousel-slide {
  flex-shrink: 0;
  overflow: hidden;
  width: 320px;
  height: 350px;
  display: flex;
  justify-content: center;
  align-items: center;
  /* transition-property: all;
  transition-duration: 1s;
  transition-timing-function: ease; */
  cursor: pointer;
}

.carousel-slide.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  width: 540px;
  z-index: 2;
}

.slide-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  /* background: #fff; */
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  padding: 25px;
  box-sizing: border-box;
  transition: all 0.3s ease;
  position: relative;
}

/* .carousel-slide.active .slide-content {
  transform: scale(1.08);
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.2);
} */

.default-card {
  text-align: center;
}

.default-card h3 {
  margin-bottom: 15px;
  color: #3498db;
  font-size: 22px;
}

.default-card p {
  color: #7f8c8d;
  line-height: 1.6;
}

.card-number {
  position: absolute;
  top: 15px;
  right: 15px;
  width: 30px;
  height: 30px;
  background: #3498db;
  color: white;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  font-size: 14px;
}

.nav-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: white;
  border: none;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  font-size: 28px;
  color: #3498db;
  cursor: pointer;
  z-index: 3;
  transition: all 0.3s ease;
}

.nav-button:hover {
  background: #3498db;
  color: white;
  box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
}

.nav-button.prev {
  left: -30px;
}

.nav-button.next {
  right: -30px;
}

.indicators {
  display: flex;
  justify-content: center;
  margin-top: 25px;
  gap: 12px;
}

.indicator {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: #dfe6e9;
  cursor: pointer;
  transition: all 0.3s ease;
}

.indicator.active {
  background: #3498db;
  transform: scale(1.3);
}
</style>
